package me.zhengjie.modules.quartz.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiaofang.applet.common.util.RedisKeyUtil;
import com.qiaofang.applet.service.member.domain.Employee;
import com.qiaofang.applet.service.member.service.EmployeeService;
import com.qiaofang.applet.service.other.domain.CityCompany;
import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.service.CityCompanyService;
import com.qiaofang.applet.service.other.service.CorporationService;
import com.qiaofang.common.request.DataRequest;
import com.qiaofang.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.quartz.service.constants.SyncConstants;
import me.zhengjie.modules.quartz.service.dto.SyncCommon;
import me.zhengjie.modules.sync.response.EmployeeCountDTO;
import me.zhengjie.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Component
public class EmpInspectionBrushTask {

    private static final String EMP_INSPECTION_COUNT_SYNC_API = "/api/dataprocessing/syncData/getInspectionCountList";

    @Autowired
    private CorporationService corporationService;

    @Autowired
    private CityCompanyService cityCompanyService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisUtils redisUtils;


    private RestTemplate template;

    {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(300000);
        requestFactory.setReadTimeout(300000);
        template = new RestTemplate(requestFactory);
    }


    public void run() {
        String taskKey = RedisKeyUtil.getTaskKey(this.getClass().getSimpleName());
        if (redisUtils.hasKey(taskKey)){
            return;
        }
        redisUtils.set(taskKey, "", 30, TimeUnit.MINUTES);
        log.info("EmpHistoryBrushTask run start");
        Corporation corporation = new Corporation();
        corporation.setDeleted(Boolean.FALSE);
        corporation.setV20Flag(Boolean.FALSE);
        Iterable<Corporation> list = corporationService.findAll(Example.of(corporation));
        list.forEach(item -> {
            String corporationCode = item.getCorporationCode();
            if (StringUtil.isEmpty(item.getPullDomain())) {
                log.error("集团:{} 的同步数据域名未配置", corporationCode);
                return;
            }

            Criteria criteria = Criteria.where("corporationCode").is(corporationCode).and("status").is(1);
            List<CityCompany> companies = mongoTemplate.find(new Query(criteria), CityCompany.class);
            companies.forEach(company -> {
                SyncCommon syncCommon = new SyncCommon();
                syncCommon.setCorporationCode(item.getCorporationCode());
                syncCommon.setAppId(item.getPullAppId());
                syncCommon.setAppKey(item.getPullAppKey());
                syncCommon.setDomain(item.getPullDomain());
                syncCommon.setCityCode(company.getCityCode());
                syncCommon.setCompanyUuid(company.getCompanyUuid());

                log.info("开始处理公司:{}的经纪人数据，开始时间:{}", company.getCompanyUuid(), new Date());
                updateEmployee(syncCommon, EMP_INSPECTION_COUNT_SYNC_API);
                log.info("完成处理公司:{}的经纪人数据，结束时间:{}", company.getCompanyUuid(), new Date());
            });
        });
        log.info("EmpHistoryBrushTask run end");
        redisUtils.del(taskKey);
    }

    private void updateEmployee(SyncCommon syncCommon, String apiUrl) {
        List<EmployeeCountDTO> countList = httpRequestData(syncCommon, apiUrl);
        if (CollectionUtils.isEmpty(countList)){
            return;
        }
        Map<String, BigDecimal> empCountMap = countList.stream().collect(Collectors.toMap(EmployeeCountDTO::getEmployeeUuid, EmployeeCountDTO::getCount, (k1, k2) -> k1));
        Set<String> set = empCountMap.keySet();
        Criteria criteria = Criteria.where("employeeUuid").in(set).and("companyUuid").is(syncCommon.getCompanyUuid());
        List<Employee> employeeList = mongoTemplate.find(new Query(criteria), Employee.class);
        if (CollectionUtils.isEmpty(employeeList)){
            return;
        }
        for (Employee employee : employeeList) {
            String employeeUuid = employee.getEmployeeUuid();
            BigDecimal count = empCountMap.get(employeeUuid);
            if (count == null) {
                continue;
            }
            employee.setInspectionCount(count);
        }
        employeeService.saveAll(employeeList);
        log.info("保存经纪人带看数据成功，保存条数：{}", employeeList.size());

    }

    private HttpHeaders getHeaders(SyncCommon syncCommon) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("X-AUTH-APP-ID", syncCommon.getAppId());
        headers.add("X-AUTH-KEY", syncCommon.getAppKey());
        headers.add("companyUuid", syncCommon.getCompanyUuid());
        log.info("========>headers:{}", JSON.toJSONString(headers));
        return headers;
    }

    private List<EmployeeCountDTO> httpRequestData(SyncCommon syncCommon, String apiUrl) {
        HttpHeaders headers = getHeaders(syncCommon);
        DataRequest dataRequest = new DataRequest();
        String url = syncCommon.getDomain() + apiUrl;
        String result = null;
        log.info("sync params {},header {}", dataRequest, headers);
        try {
            result = template.postForObject(url, new HttpEntity<>(dataRequest, headers), String.class);
            log.info("sync result {}", result);
        } catch (Exception e) {
            log.error("httpRequest error", e);
        }

        if (Objects.isNull(result)) {
            return null;
        }
        JSONObject resultObject = JSON.parseObject(result);
        if (null == resultObject) {
            return null;
        }
        String responseCode = resultObject.getString("responseCode");
        if (!SyncConstants.ON.equals(responseCode)) {
            String responseMessage = resultObject.getString("responseMessage");
            log.info("sync error {}", responseMessage);
            return null;
        }
        if (Objects.isNull(resultObject)) {
            return null;
        }
        JSONArray data = resultObject.getJSONArray("data");
        return data.toJavaList(EmployeeCountDTO.class);
    }
}
